//
//  MusicTableViewController.m
//  XMLY
//
//  Created by lanou on 15/11/9.
//  Copyright © 2015年 曾杰. All rights reserved.
//

#import "MusicTableViewController.h"
#import "MusicViewCell.h"
#import "PKRequestManager.h"
#import "MusicDetailViewController.h"
#import "MJRefresh.h"
#import "NetConnectView.h"
#import "CheckNetConnect.h"
@interface MusicTableViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong)NSMutableArray * dataArr;
@property (nonatomic,strong)MusicDetailViewController * detailVC;
@property (nonatomic, strong)NetConnectView * connectView;
@property (nonatomic, strong)UITableView * mainTabelView;
@property (nonatomic, assign)NSInteger pageId;
@end

@implementation MusicTableViewController

-(NSMutableArray *)dataArr
{
    if (_dataArr==nil) {
        self.dataArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArr;
}

-(void)requestMusicData
{
    NSString * pageId =[NSString stringWithFormat:@"pageId=%ld",(long)self.pageId];
    NSRange range = [self.urlStr rangeOfString:@"pageId=1"];
    NSString * newUrl = [self.urlStr stringByReplacingCharactersInRange:range withString:pageId];
    
        [PKRequestManager requestWithType:GET urlString:newUrl parDic:nil finish:^(NSData *data) {
          
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
                           NSArray * array = [dic objectForKey:@"list"];
                NSString * totalCount = [dic objectForKey:@"totalCount"];
                
                for (NSDictionary * dict in array) {
                    MusicModel * model = [[MusicModel alloc]init];
                    [model setValuesForKeysWithDictionary:dict];
                    [model setValue:totalCount forKey:@"totalCount"];
                    [self.dataArr addObject:model];
                }
                [self.mainTabelView reloadData];
                [self.mainTabelView.header endRefreshing];
                [self.mainTabelView.footer endRefreshing];
         
            

        } error:^(NSError *error) {
            NSLog(@"%@",error);
        }];
        
      
}



- (void)viewDidLoad {
    [super viewDidLoad];
    _mainTabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-100) style:(UITableViewStylePlain)];
    self.mainTabelView.delegate = self;
    self.mainTabelView.dataSource = self;
    [self.mainTabelView registerClass:[MusicViewCell class] forCellReuseIdentifier:@"cell"];
    self.mainTabelView.rowHeight = 120;
    __weak typeof(self) weakSelf = self;
    self.mainTabelView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self.dataArr removeAllObjects];
        [weakSelf checkNetConnectState];
       
        
    }];
    self.pageId=1;
  self.mainTabelView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.pageId++;
            
            [weakSelf checkNetConnectState];
        }];
    [self checkNetConnectState];
}

- (void)checkNetConnectState{
    
    BOOL netState = [[CheckNetConnect shareConnect] netConnectState];
    if (netState == YES) {
         [self.view addSubview:_mainTabelView];
        _connectView.frame = CGRectMake(0, - SCREEN_HEIGHT - 20, SCREEN_WIDTH, SCREEN_HEIGHT - 50) ;
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        [self requestMusicData];
        
    }else{
        
        _connectView = [[NetConnectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50)];
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.view addSubview:_connectView];
    }
    
}

// 重新请求数据
- (void)retryRequest{
    NSLog(@"重新刷新数据");
    [self checkNetConnectState];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MusicViewCell *cell = [self.mainTabelView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    MusicModel * model = self.dataArr[indexPath.row];
    if ([model.totalCount integerValue] ==self.dataArr.count) {
        [self.mainTabelView.footer noticeNoMoreData];
    }
       [cell configMusicCellWithModel:model];
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    _detailVC = [[MusicDetailViewController alloc]init];
    MusicModel * model = self.dataArr[indexPath.row];
    _detailVC.albumId = model.albumId;
    [self presentViewController:_detailVC animated:YES completion:nil];
    
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
